import { Component, ViewChild } from '@angular/core';
import { DataTableComponent, DialogService, DrawerService, IDrawerOpenResult, TableStyleData, TableWidthConfig } from '@devui';
import { DataSharingService } from 'src/app/@core/services/dataSharing/data-sharing.service';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import { LogComponent } from 'src/app/@shared/components/log/log.component';
import { environment } from 'src/environments/environment';
import { ReviewDocComponent } from '../../basic-data/user-center/review-doc/review-doc.component';
import { DisApprovalReasonComponent } from '../dis-approval-reason/dis-approval-reason.component';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { Router } from '@angular/router';
import * as mockSettlementData from './mock-settlement-data.json';
import { PurchaseService } from 'src/app/@core/services/purchase/purchase.service';
import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';

@Component({
  selector: 'app-purchase-settlement',
  templateUrl: './purchase-settlement.component.html',
  styleUrls: ['./purchase-settlement.component.scss']
})
export class PurchaseSettlementComponent {
  pager = {
      total: 20,
      pageIndex: 1,
      pageSize: 20
    };
    results: IDrawerOpenResult;
    pageSizeOptions = [10, 20, 30, 50, 100];
    tableData = [];
    dataTableOptions = {
      columns: [
        {
          field: 'code',
          header: '操作',
          fieldType: 'text',
          fixedLeft: "80px",
        },
        {
          field: 'settlementNum',
          header: '付款单号',
          fieldType: 'text',
          fixedLeft: "280px",
        },
        {
          field: 'settlementDate',
          header: '付款日期',
          fieldType: 'text'
        },
        {
          field: 'purchaseOrderNum',
          header: '采购订单号',
          fieldType: 'text'
        },
        {
          field: 'supplier',
          header: '供应商',
          fieldType: 'text'
        },
        {
          field: 'supplierFullName',
          header: '供应商全称',
          fieldType: 'text'
        },
        {
          field: 'businessPerson',
          header: '业务员',
          fieldType: 'text'
        },
        {
          field: 'department',
          header: '部门',
          fieldType: 'text'
        },
        {
          field: 'settlementAmount',
          header: '付款金额（含税）',
          fieldType: 'text'
        },
        {
          field: 'settlementAmountNoTax',
          header: '付款金额（不含税）',
          fieldType: 'text'
        },
        {
          field: 'taxAmount',
          header: '税额',
          fieldType: 'text'
        },
        {
          field: 'settlementStatus',
          header: '付款状态',
          fieldType: 'text'
        },
        {
          field: 'paymentStatus',
          header: '付款状态',
          fieldType: 'text'
        },
        {
          field: 'isClosed',
          header: '是否结案',
          fieldType: 'text'
        },
        {
          field: 'remark',
          header: '备注',
          fieldType: 'text'
        },
        {
          field: 'attachment',
          header: '附件',
          fieldType: 'text'
        },
        {
          field: 'creator',
          header: '制单人',
          fieldType: 'text'
        },
        {
          field: 'createDate',
          header: '制单日期',
          fieldType: 'text'
        },
        {
          field: 'approvalStatus',
          header: '审核状态',
          fieldType: 'text',
          fixedRight: '0px'
        },
      ]
    };
    tableWidthConfig: TableWidthConfig[] = [
      {
        field: 'checkbox',
        width: '80px'
      },
      {
        field: '操作',
        width: '200px'
      },
      {
        field: '付款单号',
        width: '180px'
      },
      {
        field: '付款日期',
        width: '150px'
      },
      {
        field: '采购订单号',
        width: '180px'
      },
      {
        field: '供应商',
        width: '150px'
      },
      {
        field: '供应商全称',
        width: '170px'
      },
      {
        field: '业务员',
        width: '120px'
      },
      {
        field: '部门',
        width: '120px'
      },
      {
        field: '付款金额（含税）',
        width: '150px'
      },
      {
        field: '付款金额（不含税）',
        width: '160px'
      },
      {
        field: '税额',
        width: '120px'
      },
      {
        field: '付款状态',
        width: '120px'
      },
      {
        field: '付款状态',
        width: '120px'
      },
      {
        field: '是否结案',
        width: '120px'
      },
      {
        field: '备注',
        width: '150px'
      },
      {
        field: '附件',
        width: '100px'
      },
      {
        field: '制单人',
        width: '120px'
      },
      {
        field: '制单日期',
        width: '150px'
      },
      {
        field: '审核状态',
        width: '120px'
      }
    ]//表格宽度配置
    dataTableOptions2 = {
      columns: [
        {
          field: 'action',
          header: '操作',
          fieldType: 'text',
        },
        {
          field: 'materialCode',
          header: '物料编码',
          fieldType: 'text',
        },
        {
          field: 'materialName',
          header: '物料名称',
          fieldType: 'text',
        },
        {
          field: 'materialSpec',
          header: '物料规格',
          fieldType: 'text',
        },
        {
          field: 'materialUnit',
          header: '物料单位',
          fieldType: 'text',
        },
        {
          field: 'purchaseQuantity',
          header: '采购数量',
          fieldType: 'text',
        },
        {
          field: 'receivedQuantity',
          header: '已到货数量',
          fieldType: 'text',
        },
        {
          field: 'settlementQuantity',
          header: '付款数量',
          fieldType: 'text'
        },
        {
          field: 'unitPrice',
          header: '单价（不含税）',
          fieldType: 'text'
        },
        {
          field: 'unitPriceWithTax',
          header: '单价（含税）',
          fieldType: 'text'
        },
        {
          field: 'taxRate',
          header: '税率',
          fieldType: 'text'
        },
        {
          field: 'settlementAmount',
          header: '付款金额（不含税）',
          fieldType: 'text'
        },
        {
          field: 'settlementAmountWithTax',
          header: '付款金额（含税）',
          fieldType: 'text'
        },
        {
          field: 'taxAmount',
          header: '税额',
          fieldType: 'text'
        },
        {
          field: 'remark',
          header: '备注',
          fieldType: 'text'
        }
      ]
    };//表头数据
    tableWidthConfig2: TableWidthConfig[] = [
      {
        field: '操作',
        width: '120px'
      },
      {
        field: '物料编码',
        width: '150px'
      },
      {
        field: '物料名称',
        width: '150px'
      },
      {
        field: '物料规格',
        width: '150px'
      },
      {
        field: '物料单位',
        width: '120px'
      },
      {
        field: '采购数量',
        width: '120px'
      },
      {
        field: '已到货数量',
        width: '130px'
      },
      {
        field: '付款数量',
        width: '120px'
      },
      {
        field: '单价（不含税）',
        width: '140px'
      },
      {
        field: '单价（含税）',
        width: '130px'
      },
      {
        field: '税率',
        width: '100px'
      },
      {
        field: '付款金额（不含税）',
        width: '160px'
      },
      {
        field: '付款金额（含税）',
        width: '150px'
      },
      {
        field: '税额',
        width: '120px'
      },
      {
        field: '备注',
        width: '150px'
      }
    ];//表格宽度配置
    allColumns = [
      {
        field: 'checkbox',
        header: 'checkbox',
        width: '80px',
        checked: true,
        disabled: true,
        fieldType: 'checkbox'
      },
      {
        field: '操作',
        header: '操作',
        width: '200px',
        checked: true,
        disabled: true,
        fieldType: 'text',
        fixedLeft: "80px",
      },
      {
        field: '付款单号',
        header: '付款单号',
        width: '180px',
        checked: true,
        disabled: true,
        fieldType: 'text',
        fixedLeft: "280px",
      },
      {
        field: '付款日期',
        header: '付款日期',
        width: '150px',
        checked: true,
        disabled: false,
        fieldType: 'text'
      },
      {
        field: '采购订单号',
        header: '采购订单号',
        width: '180px',
        checked: true,
        disabled: false,
        fieldType: 'text'
      },
      {
        field: '供应商',
        header: '供应商',
        width: '150px',
        checked: true,
        disabled: false,
        fieldType: 'text'
      },
      {
        field: '供应商全称',
        header: '供应商全称',
        width: '170px',
        checked: true,
        disabled: false,
        fieldType: 'text'
      },
      {
        field: '业务员',
        header: '业务员',
        width: '120px',
        checked: true,
        disabled: false,
        fieldType: 'text'
      },
      {
        field: '部门',
        header: '部门',
        width: '120px',
        checked: true,
        disabled: false,
        fieldType: 'text'
      },
      {
        field: '付款金额（含税）',
        header: '付款金额（含税）',
        width: '150px',
        checked: true,
        disabled: false,
        fieldType: 'text'
      },
      {
        field: '付款金额（不含税）',
        header: '付款金额（不含税）',
        width: '160px',
        checked: true,
        disabled: false,
        fieldType: 'text'
      },
      {
        field: '税额',
        header: '税额',
        width: '120px',
        checked: true,
        disabled: false,
        fieldType: 'text'
      },
      {
        field: '付款状态',
        header: '付款状态',
        width: '120px',
        checked: true,
        disabled: false,
        fieldType: 'text'
      },
      {
        field: '付款状态',
        header: '付款状态',
        width: '120px',
        checked: true,
        disabled: false,
        fieldType: 'text'
      },
      {
        field: '是否结案',
        header: '是否结案',
        width: '120px',
        checked: true,
        disabled: false,
        fieldType: 'text'
      },
      {
        field: '备注',
        header: '备注',
        width: '150px',
        checked: true,
        disabled: false,
        fieldType: 'text'
      },
      {
        field: '附件',
        header: '附件',
        width: '100px',
        checked: true,
        disabled: false,
        fieldType: 'text'
      },
      {
        field: '制单人',
        header: '制单人',
        width: '120px',
        checked: true,
        disabled: false,
        fieldType: 'text'
      },
      {
        field: '制单日期',
        header: '制单日期',
        width: '150px',
        checked: true,
        disabled: false,
        fieldType: 'text'
      },
      {
        field: '审核状态',
        header: '审核状态',
        width: '120px',
        checked: true,
        disabled: true,
        fieldType: 'text',
        fixedRight: '0px'
      },
    ]
    msgs: { severity: any; summary: any; content: any; }[]
    fifter = {
      PageSize: 20,
      PageNumber: 1,
      StartTime: '',
      EndTime: '',
      SettlementNum: '',
      PurchaseOrderNum: '',
      Supply:'',
      SettlementStatus: '',
      PaymentStatus: '',
      ApprovalStatus: '',
      isClosed: null,
    }
    styleSetting: TableStyleData = {
      size: 'sm',
      borderType: '',
      striped: false,
      shadowType: 'embed'
    };
    Customer: any = []
    creatTime: any = []
    splitBarSize = '0px';
    partDetailHeight = '100%'
    status=['待付款','部分付款','已付款','已取消']
    @ViewChild(DataTableComponent, { static: true }) datatable: DataTableComponent;
    checkedIds: any = []
    partDetail: any =[]
    selectedRowIndex: any;
    showDetailId: any;
    constructor(private SharedMethodService: SharedMethodService, private Router: Router, private DialogService: DialogService, private DrawerService: DrawerService, private dataSharingService: DataSharingService, private PurchaseService: PurchaseService, private dialogService: DialogService,private drawerService: DrawerService,private ReviewRolesService: ReviewRolesService) { }
    ngOnInit(): void {
      this.filter();
    }

    // 顶部打印：仅允许勾选一条采购付款单
    printSelected(): void {
      const rows = this.CheckedRows || [];
      if (!rows.length) {
        this.showToast('warn', '提示', '请勾选一条采购付款单');
        return;
      }
      if (rows.length !== 1) {
        this.showToast('warn', '提示', '一次只能打印一条采购付款单');
        return;
      }
      const row = rows[0];
      const html = this.buildPrintHtml(row);
      const iframe = document.createElement('iframe');
      iframe.style.position = 'fixed';
      iframe.style.right = '0';
      iframe.style.bottom = '0';
      iframe.style.width = '0';
      iframe.style.height = '0';
      iframe.style.border = '0';
      iframe.style.visibility = 'hidden';
      document.body.appendChild(iframe);

      const doc = (iframe.contentDocument || iframe.contentWindow?.document) as Document | undefined;
      if (!doc) {
        document.body.removeChild(iframe);
        this.showToast('error', '错误', '无法初始化打印窗口');
        return;
      }
      doc.open();
      doc.write(html);
      doc.close();

      setTimeout(() => {
        try {
          iframe.contentWindow?.focus();
          iframe.contentWindow?.print();
        } finally {
          setTimeout(() => {
            if (iframe && iframe.parentNode) {
              iframe.parentNode.removeChild(iframe);
            }
          }, 400);
        }
      }, 200);
    }

    // 构建采购付款单打印模板
    private buildPrintHtml(order: any): string {
      const parts = order?.settlementParts || [];
      const toNum = (x: any) => { const n = Number(x); return isNaN(n) ? 0 : n; };
      const to2 = (n: any) => typeof n === 'number'
        ? n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
        : (n ?? '');
      const fmtDate = (d: any) => {
        if (!d) return '';
        const dt = new Date(d); if (isNaN(dt.getTime())) return d;
        const y = dt.getFullYear(); const m = String(dt.getMonth()+1).padStart(2,'0'); const da = String(dt.getDate()).padStart(2,'0');
        return `${y}-${m}-${da}`;
      };
      const firstOr = (u: string) => (u && u.split(',')[0]) || '';
      const absUrl = (u: string) => {
        if (!u) return '';
        if (/^https?:\/\//i.test(u)) return u;
        const base = (environment.modifiedApiUrl || '').replace(/\/+$/, '');
        const path = ('' + u).replace(/^\/+/, '');
        return base ? `${base}/${path}` : u;
      };

      const sumQty = parts.reduce((s: number, p: any) => s + toNum(p?.settlementQuantity), 0);
      const sumAmtNoTax = parts.reduce((s: number, p: any) => s + toNum(p?.settlementAmount), 0);
      const sumAmtWithTax = parts.reduce((s: number, p: any) => s + toNum(p?.settlementAmountWithTax), 0);
      const sumTax = parts.reduce((s: number, p: any) => s + toNum(p?.taxAmount), 0);

      const rows = parts.map((p: any, i: number) => `
        <tr>
          <td>${i + 1}</td>
          <td>${p?.materialCode ?? ''}</td>
          <td>${p?.materialName ?? ''}</td>
          <td>${p?.materialSpec ?? ''}</td>
          <td>${p?.materialUnit ?? ''}</td>
          <td class="num">${to2(toNum(p?.purchaseQuantity))}</td>
          <td class="num">${to2(toNum(p?.receivedQuantity))}</td>
          <td class="num">${to2(toNum(p?.settlementQuantity))}</td>
          <td class="num">${to2(toNum(p?.unitPrice))}</td>
          <td class="num">${to2(toNum(p?.unitPriceWithTax))}</td>
          <td class="num">${to2(toNum(p?.taxRate))}%</td>
          <td class="num">${to2(toNum(p?.settlementAmount))}</td>
          <td class="num">${to2(toNum(p?.settlementAmountWithTax))}</td>
          <td class="num">${to2(toNum(p?.taxAmount))}</td>
          <td>${p?.remark ?? ''}</td>
        </tr>`).join('');

      const style = `
        <style>
        @page { size: A4; margin: 10mm; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', 'PingFang SC', 'Microsoft YaHei', sans-serif; }
        .sheet { width: 210mm; min-height: 297mm; padding: 12mm; margin: 0 auto; }
        .header { display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; }
        .header .company { font-size: 12px; }
        .header .title { text-align: center; font-size: 24px; font-weight: 700; letter-spacing: 2px; }
        .hr { border-top: 2px solid #333; margin: 6px 0 10px; }
        .info { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px 24px; font-size: 12px; }
        table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        th, td { border: 1px solid #333; padding: 6px 8px; font-size: 12px; }
        th { background: #fafafa; }
        .num { text-align: right; }
        </style>`;

      const now = new Date().toLocaleString('zh-CN');
      const html = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"/>${style}</head><body>
        <div class="sheet">
          <div class="header">
            <div class="company">${order?.company ?? '公司抬头'}</div>
            <div class="title">采购付款单</div>
            <div></div>
          </div>
          <div class="hr"></div>
          <div class="info">
            <div><strong>付款单号：</strong>${order?.settlementNum ?? ''}</div>
            <div><strong>付款日期：</strong>${fmtDate(order?.settlementDate)}</div>
            <div><strong>采购订单号：</strong>${order?.purchaseOrderNum ?? ''}</div>
            <div><strong>供应商：</strong>${order?.supplyChineseName ?? order?.supplyShortName ?? ''}</div>
            <div><strong>业务员：</strong>${order?.purchaseManName ?? ''}</div>
            <div><strong>部门：</strong>${order?.departmentName ?? ''}</div>
            <div><strong>备注：</strong>${order?.remark ?? ''}</div>
          </div>
          <table>
            <thead>
              <tr>
                <th style="width:44px;">序</th>
                <th style="width:120px;">物料编码</th>
                <th style="width:140px;">物料名称</th>
                <th style="width:140px;">规格/型号</th>
                <th style="width:60px;">单位</th>
                <th style="width:90px;" class="num">采购数量</th>
                <th style="width:90px;" class="num">到货数量</th>
                <th style="width:90px;" class="num">付款数量</th>
                <th style="width:110px;" class="num">单价(不含税)</th>
                <th style="width:110px;" class="num">单价(含税)</th>
                <th style="width:70px;" class="num">税率</th>
                <th style="width:130px;" class="num">金额(不含税)</th>
                <th style="width:130px;" class="num">金额(含税)</th>
                <th style="width:110px;" class="num">税额</th>
                <th>备注</th>
              </tr>
            </thead>
            <tbody>
              ${rows || '<tr><td colspan="15" style="text-align:center;">无明细</td></tr>'}
              <tr>
                <td colspan="7"><strong>合计</strong></td>
                <td class="num">${to2(sumQty)}</td>
                <td></td>
                <td></td>
                <td></td>
                <td class="num">${to2(sumAmtNoTax)}</td>
                <td class="num">${to2(sumAmtWithTax)}</td>
                <td class="num">${to2(sumTax)}</td>
                <td></td>
              </tr>
            </tbody>
          </table>
          <div class="info" style="margin-top:8px;">
            <div><strong>付款金额（含税）：</strong>${to2(order?.settlementAmount)}</div>
            <div><strong>付款金额（不含税）：</strong>${to2(order?.settlementAmountNoTax)}</div>
            <div><strong>税额：</strong>${to2(order?.taxAmount)}</div>
            <div><strong>付款状态：</strong>${order?.paymentStatus ?? ''}</div>
          </div>
          <div style="display:flex; justify-content:space-between; font-size:12px; margin-top:12px; border-top:1px solid #333; padding-top:6px;">
            <div>打印时间：${now}</div>
            <div>单号：${order?.settlementNum ?? ''}</div>
          </div>
        </div>
      </body></html>`;
      return html;
    }

    // 模拟数据过滤方法
    private getMockSettlementData() {
      const mockData = (mockSettlementData as any).default || mockSettlementData;
      let filteredData = [...mockData.items];

      // 根据筛选条件过滤数据
      if (this.fifter.SettlementNum) {
        filteredData = filteredData.filter(item =>
          item.settlementNum.includes(this.fifter.SettlementNum)
        );
      }

      if (this.fifter.PurchaseOrderNum) {
        filteredData = filteredData.filter(item =>
          item.purchaseOrderNum.includes(this.fifter.PurchaseOrderNum)
        );
      }

      if (this.fifter.Supply) {
        filteredData = filteredData.filter(item =>
          item.supplyShortName.includes(this.fifter.Supply) ||
          item.supplyChineseName.includes(this.fifter.Supply)
        );
      }

      if (this.fifter.SettlementStatus) {
        filteredData = filteredData.filter(item =>
          item.settlementStatus === this.fifter.SettlementStatus
        );
      }

      // 时间范围过滤
      if (this.fifter.StartTime && this.fifter.EndTime) {
        const startTime = new Date(this.fifter.StartTime).getTime();
        const endTime = new Date(this.fifter.EndTime).getTime();
        filteredData = filteredData.filter(item => {
          const itemTime = new Date(item.settlementDate).getTime();
          return itemTime >= startTime && itemTime <= endTime;
        });
      }

      // 分页处理
      const startIndex = (this.fifter.PageNumber - 1) * this.fifter.PageSize;
      const endIndex = startIndex + this.fifter.PageSize;
      const paginatedData = filteredData.slice(startIndex, endIndex);

      return {
        code: 200,
        items: paginatedData,
        totalCount: filteredData.length,
        pageNumber: this.fifter.PageNumber,
        pageSize: this.fifter.PageSize
      };
    }
    filter() {
      // 使用模拟数据替代API调用
      const mockResponse = this.getMockSettlementData();

      setTimeout(() => { // 模拟异步请求
        this.tableData = mockResponse.items;
        this.pager.total = mockResponse.totalCount;
        if(this.showDetailId){
          this.showDetail(this.tableData.find((item) => item.settlementId == this.showDetailId), this.selectedRowIndex);
        }
      }, 100);

      // 原API调用代码（已注释）
      // this.PurchaseService.getPaurchaseOrder(this.fifter).subscribe(
      //   (res:any)=>{
      //     this.tableData = res.items
      //     this.pager.total = res.totalCount
      //     if(this.showDetailId){
      //       this.showDetail(this.tableData.find((item) => item.settlementId == this.showDetailId), this.selectedRowIndex);
      //     }
      //   },
      //   (error:any)=>{
      //     this.SharedMethodService.handleError(error).subscribe(
      //       res=>{
      //         this.showToast('error', '错误', res.content);
      //       }
      //     )
      //   }
      // )
    }
    filter2() {
      this.fifter.PageNumber = 1;

      // 使用模拟数据替代API调用
      const mockResponse = this.getMockSettlementData();

      setTimeout(() => { // 模拟异步请求
        this.tableData = mockResponse.items;
        this.pager.total = mockResponse.totalCount;
        this.fifter.PageSize = mockResponse.pageSize;
        this.fifter.PageNumber = mockResponse.pageNumber;
      }, 100);

      // 原API调用代码（已注释）
      // this.PurchaseService.getPaurchaseOrder(this.fifter).subscribe(
      //   (res:any)=>{
      //     this.tableData = res.items
      //     this.pager.total = res.totalCount
      //     this.fifter.PageSize = res.pageSize
      //     this.fifter.PageNumber = res.pageNumber
      //   },(error:any)=>{
      //     console.log(error)
      //   }
      // )
    }
    reset() {
      this.fifter = {
        PageSize: 20,
        PageNumber: 1,
        StartTime: '',
        EndTime: '',
        SettlementNum: '',
        PurchaseOrderNum: '',
        Supply:'',
        SettlementStatus: '',
        PaymentStatus: '',
        ApprovalStatus: '',
        isClosed: null,
      }
      this.creatTime = []
      this.filter()
    }
    creat() {
      this.Router.navigate(['/pages/purchase/add-purchase-payment'])
    }
    edit(id: any) {
      this.Router.navigate(['/pages/purchase/purchase-settlement-edit/', id])
    }
    delete(id?: any, dialogtype?: string) {
      const results = this.DialogService.open({
        id: 'Add',
        maxHeight: '400px',
        width: '400px',
        backdropCloseable: true,
        data: "",
        title: '删除',
        content: '删除后将无法恢复该数据！',
        dialogtype: dialogtype,
        onClose: () => {

        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              if(id){
                this.PurchaseService.deletePurchaseOrder([id]).subscribe(
                 res=>{
                  this.showToast('success', '成功', '删除成功');
                  this.filter()
                  this.cleared()
                 },(error) => {
                  if(error.status==404){
                    this.showToast('error', '失败', '服务器连接失败');
                  }else{
                    this.showToast('error', '失败', error.error);
                  }
                }
                )
              }else{
                this.PurchaseService.deletePurchaseOrder(this.checkedIds).subscribe(
                  res=>{
                   this.showToast('success', '成功', '删除成功');
                   this.filter()
                   this.cleared()
                  },(error:any)=>{
                   this.SharedMethodService.handleError(error).subscribe(
                     res=>{
                       this.showToast('error', '错误', res.content);
                     }
                   )
                  }
                 )
              }
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
    onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; }) {
      this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem, this.datatable)
    }
    getCheckedRows() {
      this.SharedMethodService.getCheckedRows(this.datatable, 'purchaseOrderId').subscribe((data: any) => {
        this.checkedIds = data;
      })
      this.SharedMethodService.getCheckedRows(this.datatable, 'purchaseOrderNum').subscribe((data: any) => {
        this.checkedCodes = data;
      })
    }//获取选中行
    CheckedRows = []
    getCheckedRowsData() {
      this.SharedMethodService.getCheckedRowsData(this.datatable).subscribe((data: any) => {
        this.CheckedRows = data;
      })
    }
    cleared() {
      this.SharedMethodService.cleared(this.checkedIds, this.tableData, this.datatable).subscribe((data: any) => {
        this.checkedIds = data;
      })
    }//清空选中行
    pageIndexChange($event: any) {
      this.filter();
    }//切换页码
    pageSizeChange($event: any) {
      this.filter();
    }//改变每页显示数量
    showToast(type: any, summary: any, content: any) {
      switch (type) {
        default:
          this.msgs = [{ severity: type, summary: summary, content: content }];
      }
    }//提示框
    approval(num: any) {
      this.ReviewRolesService.GetApprovalNodeInstancesPaged('审核中', num, 1, 1).subscribe(
        (res:any)=>{
          if(res.items.length>0){
            this.ReviewRolesService.ApproveNode(res.items[0].approvalNodeId, num).subscribe(
              (res) => {
                this.showToast('success', '成功', '审批成功')
                this.filter()
              },
              (error: any) => {
                this.showToast('error', '错误', error.error||'网络连接错误')
              }
            )
          }else{
            this.showToast('error', '错误', '没有需要审批的数据')
          }
        }
      )
    } //审批
    disApproval(num: any,dialogtype?:string) {
      const results = this.DialogService.open({
        id: 'Add',
        maxHeight: '600px',
        width: '400px',
        backdropCloseable: true,
        data: '',
        title: '不通过原因',
        content:DisApprovalReasonComponent ,
        dialogtype: dialogtype,
        onClose: () => {},
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              console.log(results.modalContentInstance.reason);
              this.ReviewRolesService.GetApprovalNodeInstancesPaged('审核中', num, 1, 1).subscribe(
                (res:any)=>{
                  if(res.items.length>0){
                    this.ReviewRolesService.RejectNode(res.items[0].approvalNodeId, num, results.modalContentInstance.reason).subscribe(
                      (res) => {
                        this.showToast('success', '成功', '审批成功');
                        this.filter();
                      },
                      (error: any) => {
                        this.showToast('error', '错误', error.error||'网络连接错误');
                      }
                    );
                  }else{
                    this.showToast('error', '错误', '没有需要审批的数据');
                  }
                }
              )
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }//不通过
    unApproval(id: any) {
      this.PurchaseService.auditPurchaseOrder('待审核', id).subscribe(
        res=>{
          this.showToast('success', '成功', '反审核成功');
          this.filter()
          this.cleared()
        },(error:any)=>{
          this.SharedMethodService.handleError(error).subscribe(
            res=>{
              this.showToast('error', '错误', res.content);
            }
          )
        }
      )
    }//反审批
    closed(id: any) {
      this.PurchaseService.closePurchaseRequirement(id).subscribe(
        res=>{
          this.showToast('success', '成功', '结案成功');
          this.filter()
          this.cleared()
        },(error:any)=>{
          this.SharedMethodService.handleError(error).subscribe(
            res=>{
              this.showToast('error', '错误', res.content);
            }
          )
        }
      )
    }//结案
    unClosed(id: any) {
      this.PurchaseService.closePurchaseRequirement(id).subscribe(
        res=>{
          this.showToast('success', '成功', '反结案成功');
          this.filter()
          this.cleared()
        },(error:any)=>{
          this.SharedMethodService.handleError(error).subscribe(
            res=>{
              this.showToast('error', '错误', res.content);
            }
          )
        }
      )
    }//反结案
    allLog() {
      this.PurchaseService.GetAllPurchaseOrderLogs(1,9999).subscribe((data:any)=>{
        const logData = data.items
        const columns =  [
          {
            field: '采购订单号',
            header: '采购订单号',
            fieldType: 'text'
          },
          {
            field: 'content',
            header: '日志内容',
            fieldType: 'text'
          },
          {
            field: '执行人',
            header: '执行人',
            fieldType: 'text'
          },
          {
            field: '执行时间',
            header: '执行时间',
            fieldType: 'text'
          }
        ]
        this.results = this.drawerService.open({
          drawerContentComponent: LogComponent,
          width: '40%',
          data: {data:logData,columns:columns},
          zIndex: 1000,
          isCover: false,
          fullScreen: true,
          backdropCloseable: true,
          escKeyCloseable: true,
          position: 'right',
          resizable: true,
          onClose: () => {

          },
        });
      })
    }
    GetLogsById(id: any) {
      this.PurchaseService.GetLogsByPurchaseOrderId(id,1,999).subscribe((data:any)=>{
        const logData = data.items
        const columns =  [
          {
            field: '采购订单号',
            header: '采购订单号',
            fieldType: 'text'
          },
          {
            field: 'content',
            header: '日志内容',
            fieldType: 'text'
          },
          {
            field: '执行人',
            header: '执行人',
            fieldType: 'text'
          },
          {
            field: '执行时间',
            header: '执行时间',
            fieldType: 'text'
          }
        ]
        this.results = this.drawerService.open({
          drawerContentComponent: LogComponent,
          width: '40%',
          data: {data:logData,columns:columns},
          zIndex: 1000,
          isCover: false,
          fullScreen: true,
          backdropCloseable: true,
          escKeyCloseable: true,
          position: 'right',
          resizable: true,
          onClose: () => {

          },
        });
      })
    }
    checkCustomerIDs(customerRows: any) {
      // 如果数组长度为1或为空，直接返回true
      if (customerRows.length <= 1) {
        return true;
      }
      // 获取第一个元素的customerID
      const firstCustomerID = customerRows[0].customerID;
      // 检查数组中每个元素的customerID是否都与第一个元素的customerID相同
      return customerRows.every((row: { customerID: any; }) => row.customerID === firstCustomerID);
    }
    downloadTemplate(){
      this.PurchaseService.exportPurchaseRequirementToExcelModel().subscribe((data:any)=>{
        const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const objectUrl = URL.createObjectURL(blob);
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display:none');
        a.setAttribute('href', objectUrl);
        a.setAttribute('download', '采购订单模版.xlsx');
        a.click();
        URL.revokeObjectURL(objectUrl);
      })
    }
    file: any;
    import(event: any) {
      this.file = event.target.files[0];
       this.PurchaseService.importPurchaseRequirementFromExcel(this.file).subscribe((data:any)=>{
        const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const objectUrl = URL.createObjectURL(blob);
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display:none');
        a.setAttribute('href', objectUrl);
        a.setAttribute('download', '采购订单.xlsx');
        a.click();
        URL.revokeObjectURL(objectUrl);
        this.filter();
       })
    }
    @ViewChild('fileInput2') fileInput2: any;
    onButtonClick() {
      this.fileInput2.nativeElement.click();
    }
    download() {
      this.PurchaseService.exportPurchaseRequirementToExcel().subscribe((data:any)=>{
        const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const objectUrl = URL.createObjectURL(blob);
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display:none');
        a.setAttribute('href', objectUrl);
        a.setAttribute('download', '采购订单.xlsx');
        a.click();
        URL.revokeObjectURL(objectUrl);
      })
    }
    fujian(rowitem: any, dialogtype?: string) {
      const results = this.dialogService.open({
        title: '附件',
        width: '800px',
        backdropCloseable: false,
        data: {
          data: '销售附件',
          urls: rowitem.files,
          type: '查看'
        },
        content: AttachmentComponent,
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ]
      });
    }
    showDetail(data: any,rowIndex: any) {
      this.showDetailId = data.settlementId;
      this.partDetail = data.settlementParts,
        this.partDetailHeight = '75%'
        this.splitBarSize = '10px'
        this.selectedRowIndex = rowIndex;
    }

    viewSettlementDetail(rowItem: any) {
      // 查看付款详情的逻辑
      console.log('查看付款详情:', rowItem);
    }
    getImagesArray(fileURL: string): string[] {
      let urls = fileURL.split(',');
      urls = urls.map(url => environment.modifiedApiUrl + url);
      return urls;
    }
    creatTimeChange(event: any) {
      if(event.length === 2){
        this.fifter.StartTime = event[0].toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '/');
        this.fifter.EndTime = event[1].toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '/')
      }
    }
    ClosePurchaseOrder(isClosed: boolean) {
      if(isClosed){
        this.PurchaseService.ClosePurchaseOrder(this.checkedIds,isClosed).subscribe(
          res=>{
            this.showToast('success', '成功', '结案成功');
            this.filter()
            this.cleared()
          },(error:any)=>{
            if(error.status === 404){
              this.showToast('error', '错误', '服务器连接失败');
            }else{
              this.showToast('error', '错误', error.error);
            }
          }
        )
      }else{
        this.PurchaseService.ClosePurchaseOrder(this.checkedIds,isClosed).subscribe(
          res=>{
            this.showToast('success', '成功', '反结案成功');
            this.filter()
            this.cleared()
          },(error:any)=>{
            if(error.status === 404){
              this.showToast('error', '错误', '服务器连接失败');
            }else{
              this.showToast('error', '错误', error.error);
            }
          }
        )
      }
    }
    ClosePurchaseOrderPart(rowItem:any,isClosed: boolean) {
      if(isClosed){
        this.PurchaseService.ClosePurchaseOrderPart([rowItem.purchaseOrderPartId],isClosed).subscribe(
          res=>{
            this.showToast('success', '成功', '结案成功');
            this.filter()
          },(error:any)=>{
            if(error.status === 404){
              this.showToast('error', '错误', '服务器连接失败');
            }else{
              this.showToast('error', '错误', error.error);
            }
          }
        )
      }else{
        this.PurchaseService.ClosePurchaseOrderPart([rowItem.purchaseOrderPartId],isClosed).subscribe(
          res=>{
            this.showToast('success', '成功', '反结案成功');
            this.filter()
          },(error:any)=>{
            if(error.status === 404){
              this.showToast('error', '错误', '服务器连接失败');
            }else{
              this.showToast('error', '错误', error.error);
            }
          }
        )
      }
    }
    checkedCodes = []
    launchReview() {
      const invalidStatus = this.CheckedRows.some(row => row.status === '审核通过' || row.status === '审核中')
      if(invalidStatus){
        this.showToast('error', '错误', '请选择待审核或审核未通过的数据');
        return;
      }
      if (this.checkedCodes.length < 1) {
        this.showToast('error', '错误', '请选择要发起审核的单据');
        return;
      }
      this.ReviewRolesService.StartApprovalFlow('采购订单审核流配置',this.checkedCodes).subscribe(
        (res: any) => {
          this.showToast('success', '成功', res);
          this.filter()
          this.checkedIds = [];
          this.checkedCodes = [];
        },
        (error: any) => {
          this.showToast('error', '错误', error.error);
        }
      );
    }
    clickCode(code: string, type: string, status: string, dialogtype?: string) {
      let data = {
        code: code,
        type: type,
        disPlay: false,
      };
      const results = this.DialogService.open({
        id: 'custom',
        width: '90vw',
        maxHeight: '90vh',
        backdropCloseable: true,
        content: ReviewDocComponent,
        dialogtype: dialogtype,
        data:data,
        onClose: () => {},
        buttons: [
          {
            cssClass: 'stress',
            text: '通过',
            handler: ($event: Event) => {
              if(results.modalContentInstance.approvalNodeId){
              this.ReviewRolesService.ApproveNode(
                results.modalContentInstance.approvalNodeId,
                code
              ).subscribe((res: any) => {
                results.modalInstance.hide();
                this.showToast('success', '成功', '审批成功');
                this.filter();
              },error=>{
                this.showToast('error', '错误', error.error || '网络连接错误');
              }
            );
            }
            else{
              this.showToast('error', '错误', '没有需要审批的节点');
            }
            },
          },
          {
            cssClass: 'danger',
            text: '驳回',
            handler: ($event: Event) => {
              if(results.modalContentInstance.approvalNodeId){
                console.log()
              if(results.modalContentInstance.reason){
                this.ReviewRolesService.RejectNode(
                  results.modalContentInstance.approvalNodeId,
                  code,
                  results.modalContentInstance.reason
                ).subscribe(
                  (res) => {
                    this.showToast('success', '成功', '审批成功');
                    results.modalInstance.hide();
                    this.filter();
                  },
                  (error: any) => {
                    this.showToast(
                      'error',
                      '错误',
                      error.error || '网络连接错误'
                    );
                  }
                );
              }else{
                data.disPlay = true
                this.showToast('warn', '警告', '请填写驳回原因');
              }
            }else{
              this.showToast('error', '错误', '没有需要审批的节点');
            }
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
    onColsChanges(e:any) {
      this.allColumns = e;
      this.tableWidthConfig = [];
      this.dataTableOptions.columns = this.allColumns.slice(1).filter(t => t.checked);
      this.tableWidthConfig = this.allColumns.filter(t => t.checked);
    }
    onStyleChanges(e:any) {
      this.styleSetting = e;
    }
    getImagesArray2(fileURL: string): string[] {
      let urls = fileURL.split(',');
      urls = urls.map(url => environment.modifiedApiUrl +'/' + url);
      return urls;
    }
}
